<template>
  <div>
    <!-- 新增角色按钮 -->
    <el-row style="height: 60px">
      <el-button icon="el-icon-plus" size="small" type="primary" @click="openEdidRoleDialog('')">新增角色</el-button>
    </el-row>
    <!-- 表格 -->
    <el-table border :data="roleList">
      <el-table-column type="index" label="序号" width="120" align="center" />
      <el-table-column label="角色名称" width="240" prop="name" />
      <el-table-column label="描述" prop="description" />
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button size="small" type="success" @click="assignRole(row.id)">分配权限</el-button>
          <el-button size="small" type="primary" @click="openEdidRoleDialog(row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <!-- 分页组件 -->
      <el-pagination
        :current-page="query.page"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[4, 6, 8, 10]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>
    <!-- 新增/编辑角色的组件 -->
    <edit-role ref="editRoleRef" @get-new-roles="getRoleList" />
    <!-- 分配权限 -->
    <assign-permission ref="assignPerRef" />
  </div>
</template>

<script>
import { getRoleList, delRole } from '@/api/role'
import EditRole from './components/edit-role.vue'
import AssignPermission from './components/assign-permission.vue'
export default {
  components: {
    EditRole,
    AssignPermission
  },
  data() {
    return {
      // 角色列表
      roleList: [],
      // 查询条件
      query: {
        page: 1, // 当前页码
        pagesize: 4 // 每页显示多少条记录
      },
      total: 0 // 总记录数
    }
  },
  created() {
    // 获取角色列表
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.query)
      this.total = total
      this.roleList = rows
    },
    // 当前页码发生改变时触发
    handleCurrentChange(page) {
      this.query.page = page
      this.getRoleList()
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(size) {
      this.query.pagesize = size
      this.getRoleList()
    },
    // 删除角色
    async delRole(id) {
      try {
        await this.$confirm('您确定要删除该角色数据吗')
        // 删除
        await delRole(id)
        this.$message.success('删除成功')
        // 重新获取数据
        this.getRoleList()
      } catch {
        console.log('取消删除')
      }
    },
    // 打开新增/修改角色的组件对话框
    openEdidRoleDialog(id) {
      this.$refs.editRoleRef.open(id)
    },
    // 给角色分配权限
    assignRole(roleId) {
      this.$refs.assignPerRef.open(roleId)
    }
  }
}
</script>

<style lang="scss" scoped></style>
